package com.yh.csx.crm.appapi.controller;

import com.yh.csx.crm.core.entity.CommonResponse;
import com.yh.csx.crm.core.exception.BusinessException;
import com.yh.b2b.usercenter.facade.stub.vo.UserVO;
import com.yh.csx.crm.core.util.WebUtils;
import com.yh.csx.crm.po.SysSalesPermission;
import com.yh.csx.crm.service.PublicService;
import com.yh.csx.crm.service.SaleService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;

import java.util.concurrent.Callable;

public abstract class BaseController {
    @Autowired
    PublicService publicService;

    @Autowired
    SaleService saleService;

    protected Logger log = LoggerFactory.getLogger(this.getClass());

    protected UserVO getUserInfo() {
        return WebUtils.getUser();
    }

    protected Long getUserId() {
        return WebUtils.getUserId();
    }

    protected String getUserName() {
        return WebUtils.getUserName();
    }

    protected String getWorkNumber() {
        SysSalesPermission sales = saleService.findSalesPermission(getUserId());
        if (sales == null) throw new BusinessException("账号无权限");
        if (StringUtils.isBlank(sales.getWorkNumber())) {
            return String.valueOf(sales.getUserId());
        } else {
            return sales.getWorkNumber();
        }
    }

    protected ModelAndView visitPage(Callable<ModelAndView> callable, Option... options) {
        try {
            checkOptions(options);
            return callable.call();
        } catch (Throwable e) {
            log.error("", e);
            return null;
        }
    }

    protected <T> CommonResponse<T> visit(Runnable runnable, Option... options) {
        try {
            checkOptions(options);
            runnable.run();
            return CommonResponse.success();
        } catch (Throwable e) {
            log.error("", e);
            return CommonResponse.error(e);
        }
    }

    protected <T> CommonResponse<T> visit(Callable<T> callable, Option... options) {
        try {
            checkOptions(options);
            return CommonResponse.success(callable.call());
        } catch (Throwable e) {
            log.error("", e);
            return CommonResponse.error(e);
        }
    }

    private void checkOptions(Option[] options) {
        if (!publicService.checkUserExist(this.getUserId())) {
            throw new BusinessException("您没有查看CRM系统的权限");
        }
        for (Option option : options) {
            if (option == Option.AUTH) {
                assertAuth();
            }
        }
    }

    private void assertAuth() {
        if (WebUtils.getUser() == null) {
            throw new BusinessException("请先登录后再请求");
        }
    }

    public enum Option {
        AUTH,
        ROTS
    }
}
